package com.kexun.mvc.resolvers;

import com.alibaba.fastjson.JSON;
import com.kexun.annotation.RequestBody;
import com.kexun.entity.Manage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Parameter;

public class RequestBodyResolver implements BaseResolver {
    @Override
    public boolean supportsParameter(Parameter parameter) {
        return parameter.getAnnotation(RequestBody.class) != null;
    }

    @Override
    public Object resolveArgument(Parameter parameter, HttpServletRequest req, HttpServletResponse resp) {
        String bodyData = getBodyData(req);
        System.out.println("body:"+bodyData);
        try {
            return JSON.toJavaObject(JSON.parseObject(bodyData), parameter.getType().newInstance().getClass());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String getBodyData(HttpServletRequest request) {
        StringBuffer data = new StringBuffer();
        String line = null;
        BufferedReader reader = null;
        try {
            reader = request.getReader();
            while (null != (line = reader.readLine())) {
                data.append(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return data.toString();
    }
}
